|
|
|
Of course, your
memory changes over time. Your friend moves across country and has a new
phone number, and your friend's new phone number will replace the old one in
your memory.
|
|
Over time, as
you acquire new friends, your memory will keep changing to store different
pieces of information. Likewise, a computer's memory can change over time, if
you tell it to. Since variables are your access point to your computer's
memory, it makes sense that you'd be able to change the information in a
computer's memory; otherwise, they wouldn't be called variables
(they'd be called statics).
|
|
Why should you
care about variables? Variables are the essence of any computer program!
Without variables, computers would be useless. Imagine a program which asks
the user for two numbers and adds them together, and prints the result.
|
|
# AddTwoNumbers
Enter the first number: 2 Enter the second number: 5 The sum of
2 and 5 is 7. # Sounds simple,
right? But let's do a little role-playing to see what the computer has to do
to execute this program. Instead of this interaction between a person and a
computer, let's imagine the same kind of conversation between two people, Sol
and Frank. Sol: Hey Frank, I just learned how to add two numbers
together.
Frank: Cool!
Sol: Give me the first
number.
Frank: 2.
Sol: Ok, and give me the second
number.
Frank: 5.
Sol: Ok, here's the answer: 2 +
5 = 7.
Frank: Sheesh! This guy is unbelievable!
After Frank says "2", Sol has to store that number in his memory
somewhere. It may be stored in short-term memory, but he has to store it
somewhere before Frank gives him the second number. Even if Frank were to
give him two numbers in the same sentence, Sol would have to store the
numbers somewhere in his memory to add them together.
|
|
In the sample
program described above, the computer would most likely store "2"
in a variable, then store "5" in a variable, and then calculate the
sum by calculating the sum of the numbers store in the two variables.
|
|
|